﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace OmniKits
{
    using Utilities;

    partial class Helpers
    {
        public sealed class XmlHelper { }
        public static XmlHelper XML { get; }

        public static IEnumerable<XNode> ReadRootlessXNodes(this XmlHelper _, XmlReader reader)
            => reader.ReadRootlessXNodes();
        public static XNode[] ToRootlessXNodes(this XmlHelper _, string fragement)
            => fragement.ToRootlessXNodes();
    }
}

namespace OmniKits.Utilities
{
    public static class XmlUtility
    {
#pragma warning disable 1591

        public static IEnumerable<XNode> ReadRootlessXNodes(this XmlReader reader)
        {
            reader.MoveToContent();
            while (!reader.EOF)
            {
                var xnode = XNode.ReadFrom(reader);
                if (xnode == null)
                    yield break;
                yield return xnode;
            }
        }

        public static XNode[] ToRootlessXNodes(this string fragement)
        {
            using (var sr = new StringReader(fragement))
            {
                using (var reader = XmlReader.Create(sr, new XmlReaderSettings
                {
                    ConformanceLevel = ConformanceLevel.Fragment,
                }))
                {
                    return reader.ReadRootlessXNodes().ToArray();
                }
            }
        }
    }
}
